package com.kuizii.auth.shiro;



import com.kuizii.demo.api.SysUserService;
import com.kuizii.demo.domain.SysUserDto;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * shiro Realm
 *
 * @author
 */

/**
 * realm
 */
public class KuiziiDbRealm extends AuthorizingRealm {

    /**
     * 用户服务
     */
    @Autowired
    SysUserService userService;


    @Autowired
    Environment environment;

    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     * 限定这个Realm只支持我们自定义的JWT Token
     */
    @Override
    public boolean supports(AuthenticationToken token) {

        return token instanceof UsernamePasswordToken;
    }


    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken user = (UsernamePasswordToken) token;
        SysUserDto sysUser = userService.getUserById(user.getUsername());

        if (sysUser == null) {
            throw new UnknownAccountException("用户信息不存在！");
        }

        if (sysUser.getUserState() == -1) {
            throw new LockedAccountException("帐户已被禁用！");
        }
        if (StringUtils.isEmpty(sysUser.getPassword())) {
            throw new UnknownAccountException("用户需完善信息！");
        }
        if (sysUser.getUserState() == 0) {
            throw new UnActivityException("帐户还未开通激活！");
        }

        //盐值加密
        ByteSource byteSource = ByteSource.Util.bytes(user.getUsername());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(sysUser, sysUser.getPassword(), byteSource, getName());
        return info;
    }


    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        if (principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }

        if (!(principals.getPrimaryPrincipal() instanceof SysUserDto))
        {
            return null;
        }
        SysUserDto sysUser = (SysUserDto) principals.getPrimaryPrincipal();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //todo
        Set<String> roles = new HashSet<String>(){};
        Set<String> permissions = new HashSet<String>(){} ;
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }


}
